package com.example.mqttcar.controller;

import com.example.mqttcar.mqtt.MqttSubscriber;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/mqtt")
public class MqttPublisher {

    @Autowired
    private MqttClient mqttClient;



    @RequestMapping("/sendMessage")
    public String sendMessage(@RequestBody String message) throws Exception {
        MqttMessage mqttMessage = new MqttMessage(message.getBytes());
        mqttMessage.setQos(1); // 设置消息质量（0/1/2）
        mqttClient.publish(MqttSubscriber.topic, mqttMessage);
        return "消息已发送: " + message;
    }
}
